package com.kystar.muxplayer.ui;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.LinearLayout;
import android.widget.Spinner;
import com.kystar.muxplayer.BaseApp;
import com.kystar.muxplayer.R;
import com.kystar.muxplayer.base.SpinnerAdapter;
import com.kystar.muxplayer.base.TLog;
import com.kystar.muxplayer.manager.PvmManager;
import com.kystar.muxplayer.model.Layer;
import com.kystar.muxplayer.model.Source;
import com.kystar.muxplayer.model.SourceType;
import com.kystar.muxplayer.protocol.code.get.CG8D_SourceStatus;
import com.kystar.muxplayer.protocol.code.get.CG8E_SourceInfo;
import com.kystar.muxplayer.protocol.code.set.CS0E_LayerInfo;
import com.kystar.muxplayer.protocol.code.set.CS10_SourceInfo;
import com.kystar.muxplayer.widget.BrightnessPopupWindow;
import java.io.Serializable;
import java.util.concurrent.CountDownLatch;

@SuppressLint("CheckResult")
public class SourceSetting implements Runnable, OnItemSelectedListener {

    VHolder[] mHolders = new VHolder[8];
    Source[] mSources = new Source[8];
    private static final int[] sourceIds = {R.id.source_0, R.id.source_1, R.id.source_2,
        R.id.source_3, R.id.source_4, R.id.source_5, R.id.source_6,R.id.source_7};

    private Thread mThread;
    View mLastLinearLayout;

    private boolean onDestroy;
    private boolean onStop;
    private Context mContext;
    private View rootView;
    public SourceSetting(Context context, View rootView) {
        mContext = context;
        this.rootView = rootView;

        mSources = BaseApp.getSettings().getSources();
        for (int i = 0; i < 8; i++) {
            mHolders[i] = new VHolder(rootView.findViewById(sourceIds[i]));
            initSource(mSources[i], mHolders[i]);
        }
        onDestroy = false;
        onStop = false;
        mThread = new Thread(this);
        mThread.start();
    }

    private void initSource(Source source, VHolder holder) {
        holder.setText(R.id.source_name, source.getType().name);
        holder.setText(R.id.source_info, source.getInfo());
        Spinner spinner = holder.getView(R.id.source_channel);
        spinner.setTag(source);
        spinner.setAdapter(new SpinnerAdapter(mContext,R.layout.spinner_source_textview,R.layout.spinner_source_dropdown,R.array.source_type));
        spinner.setSelection(source.getBackup().ordinal());
        spinner.setOnItemSelectedListener(this);
        View input = holder.getView(R.id.input);
        if (source.isValid()) {
            input.setBackgroundResource(R.color.color_pvw);
        } else {
            input.setBackgroundResource(R.color.color_source_lost);
        }
        holder.itemView.setOnClickListener(v->{
            if(mLastLinearLayout!=null){
                mLastLinearLayout.setBackgroundColor(mContext.getResources().getColor(R.color.transparency));
            }
            v.setBackgroundColor(mContext.getResources().getColor(R.color.main_font_color_highlight));
            mLastLinearLayout = (LinearLayout) v;
            TLog.e("test","isClick");
        });
        holder.setOnClickListener(R.id.input,v -> {

        });
        GestureDetector detector = new GestureDetector(mContext,new SimpleOnGestureListener(){
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                View view = PvmManager.getPvmSingleInstance().getFrameLayout().getSelectView();
                if (view!=null) {
                    PvmManager.getPvmSingleInstance().switchSource(view,source);
                    return true;
                }
                return super.onDoubleTap(e);
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                if(mLastLinearLayout!=null){
                    mLastLinearLayout.setBackgroundColor(mContext.getResources().getColor(R.color.transparency));
                }
                mLastLinearLayout = holder.itemView;
                mLastLinearLayout.setBackgroundColor(mContext.getResources().getColor(R.color.main_font_color_highlight));
                TLog.e("test","isClick");
                return super.onSingleTapConfirmed(e);
            }

            @Override
            public void onLongPress(MotionEvent e) {
                Intent intent = new Intent();
//                intent.putExtra("source",source);
//                intent.putExtra("source",(Serializable)source);
                intent.putExtra("index",BaseApp.getSettings().indexOf(source));

                ClipData clipData = ClipData.newIntent("sourceData",intent);
                View.DragShadowBuilder dragShadowBuilder = new View.DragShadowBuilder(input){
                    Drawable mDrawable = mContext.getDrawable(R.drawable.sources_preview);

                    @Override
                    public void onProvideShadowMetrics(Point outShadowSize,
                        Point outShadowTouchPoint) {
                        super.onProvideShadowMetrics(outShadowSize, outShadowTouchPoint);
                    }

                    @Override
                    public void onDrawShadow(Canvas canvas) {
//                        super.onDrawShadow(canvas);
//                        canvas.drawBitmap(App.loadBitmap(source.source), null, rect, null);
                        mDrawable.setBounds(input.getLeft(),input.getTop(),input.getRight(),input.getBottom());
                        mDrawable.draw(canvas);
                    }
                };
                input.startDrag(clipData,dragShadowBuilder,input,0);
            }

        });
        input.setOnTouchListener( (v, event) -> detector.onTouchEvent(event));

        holder.setOnClickListener(R.id.source_brightness, v -> {
            BrightnessPopupWindow popupWindow = new BrightnessPopupWindow(mContext);
            popupWindow.show(v);
            popupWindow.setProgress(source.getBrightness());
            popupWindow.setOnProgressChanged(
                process -> {
                    BaseApp.send(CS10_SourceInfo.createBright(source.getSourceId(),process)).subscribe(cmd->{
                        source.setBrightness(process);
                        holder.setText(R.id.source_brightness,process+"");
                    });

                });
        });

    }

    public void onStop() {
        onStop = true;
    }

    public void onResume() {
        onStop = false;
    }

    public void onDestroy() {
        onDestroy = true;
    }


    @Override
    public void run() {
        while (!onDestroy) {
//            onDestroy = true;

            if (!onStop) {
                CountDownLatch latch = new CountDownLatch(1);//用于阻塞线程
                BaseApp.send(CG8D_SourceStatus.create()).subscribe(cmd -> {
                    boolean[] status = cmd.getStatus();
                    for (int i = 0; i < mSources.length; i++) {
                        Source source = mSources[i];
                        source.setValid(status[i]);
                        if (source.isValid()) {
                            mHolders[i].setBackgroundRes(R.id.input, R.color.color_pvw);
                        } else {
                            mHolders[i].setBackgroundRes(R.id.input,R.color.color_source_lost);
                        }
                    }
                },e->latch.countDown(), latch::countDown);
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

//                for (int i = 0; i < mSources.length; i++) {
//                    Source source = mSources[i];
//                    VHolder holder = mHolders[i];
//                    if (source.getType() == SourceType.None) continue;
//                    CountDownLatch latch2 = new CountDownLatch(3);
//                            BaseApp.send(CG8E_SourceInfo.createSourceBrightInfo(source.getSourceId())).subscribe(c -> {
////                                if (source.getBrightness() != c.getBright()) {
//                                source.setBrightness(c.getBright());
//                                holder.setText(R.id.source_brightness,source.getBrightness()+"");
////                            }
//                            },e->latch2.countDown(),latch2::countDown);
//
////                        BaseApp.send(CG8E_SourceInfo.createSourceContrastInfo(i)).subscribe(c -> {
////                            if (source.getBrightness() != c.getBright()) {
////                                source.setBrightness(c.getBright());
////                                mHolders[source.getSourceId()].setText(R.id.source_brightness,source.getBrightness()+"");
////                            }
////                        },e->latch2.countDown(), latch2::countDown);
//                        BaseApp.send(CG8E_SourceInfo.createSourceEdidInfo(source.getSourceId())).subscribe(c -> {
////                            if (!source.getEdid().equals(c.getEDID())) {
//                                source.setEdid(c.getEDID());
//                                holder.setText(R.id.source_info,source.getInfo());
////                            }
//                        },e->latch2.countDown(), latch2::countDown);
//                        BaseApp.send(CG8E_SourceInfo.createSourceBackupInfo(source.getSourceId())).subscribe(c -> {
//                            if (source.getBackup() != c.getBackup()) {
//                                source.setBackup(c.getBackup());
//                                Spinner spinner = holder
//                                    .getView(R.id.source_channel);
//                                spinner.setSelection(source.getBackup().ordinal());
//                            }
//                        },e->latch2.countDown(), latch2::countDown);
//                        try {
//                            latch2.await();
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
////                    }
////                        BaseApp.send(new CS10_SourceInfo())
//
//                }

            }

            try {
                Thread.sleep(3000);//考虑内容修改了，尝试让睡眠时间减小，使得页面刷新相应更快
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Source source = (Source) parent.getTag();
        if (source == null) return;
        if (position != source.getBackup().ordinal()) {
            TLog.e("set back source");
            SourceType type = SourceType.values()[position];
            BaseApp.send(CS10_SourceInfo.createBackUp(source.getSourceId(), type))
                .subscribe(cmd -> {
                    source.setType(type);
                }, e -> {
                    parent.setSelection(source.getType().ordinal());//设置失败，回重置回去
                });
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
